package boot.spring.util;

import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtUtils {
	/**
     * 过期时间60分钟
     */
    private static final long EXPIRE_TIME = 60 * 60 * 1000;
    /**
     * jwt 密钥
     */
    private static final String SECRET = "jwt_secret";
    
    /**
     * 生成签名，60分钟后过期
     * @param userId
     * @return token
     */
    public static String sign(String userName) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    //将userid保存到token里面
                    .withAudience(userName)
                    //60分钟后token过期
                    .withExpiresAt(date)
                    //token 的密钥
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 根据token获取userName
     * @param token
     * @return userId
     */
    public static String getUserName(String token) {
        try {
            String userName = JWT.decode(token).getAudience().get(0);
            return userName;
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    
    /**
     * 校验token
     * @param token
     */
    public static boolean checkSign(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
			DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception) {
        	 return false;
        }
    }
    
}
